package org.example.commonapi.domain;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import org.apache.commons.codec.digest.DigestUtils;
import org.example.commonapi.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

public class ExcelListener extends AnalysisEventListener<ExcelUser> {

    private UserMapper userMapper;

    private Integer role;

    private List<User> userList = new ArrayList<>();

    private static final int BATCH_COUNT = 5;


    public ExcelListener(UserMapper userMapper,Integer role) {
        this.userMapper = userMapper;
        this.role = role;
    }

    @Override
    public void invoke(ExcelUser excelUser, AnalysisContext analysisContext) {
        User user = new User();
        user.setUsername(excelUser.getUsername());
        // 以身份证后六位作为密码
        user.setPassword(DigestUtils.md5Hex(excelUser.getIdCard().substring(12)));
        user.setPhone(excelUser.getPhone());
        user.setNo(excelUser.getNo());
        user.setAddress(excelUser.getAddress());
        user.setRole(role);
        userList.add(user);
        // 达到BATCH_COUNT了，需要去存储一次数据库
        if (userList.size() >= BATCH_COUNT) {
            for (User newUser : userList) {
                user.setCreateTime(LocalDateTime.now());
                user.setUpdateTime(LocalDateTime.now());
                userMapper.insert(newUser);
            }
            // 存储完成清理 list
            userList.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        if (!userList.isEmpty()) {
            for (User newUser : userList) {
                newUser.setCreateTime(LocalDateTime.now());
                newUser.setUpdateTime(LocalDateTime.now());
                userMapper.insert(newUser);
            }
        }
    }
}
